home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / cmds / bison / bison.info-2 < prev    next >
Encoding:
Text File  |  1988-12-30  |  49.0 KB  |  1,404 lines

  1. Info file bison.info, produced by Makeinfo, -*- Text -*- from input
  2. file bison.texinfo.
  3.  
  4. This file documents the Bison parser generator.
  5.  
  6. Copyright (C) 1988 Free Software Foundation, Inc.
  7.  
  8. Permission is granted to make and distribute verbatim copies of this
  9. manual provided the copyright notice and this permission notice are
  10. preserved on all copies.
  11.  
  12. Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided also
  14. that the sections entitled ``Bison General Public License'' and
  15. ``Conditions for Using Bison'' are included exactly as in the
  16. original, and provided that the entire resulting derived work is
  17. distributed under the terms of a permission notice identical to this
  18. one.
  19.  
  20. Permission is granted to copy and distribute translations of this
  21. manual into another language, under the above conditions for modified
  22. versions, except that the text of the translations of the sections
  23. entitled ``Bison General Public License'' and ``Conditions for Using
  24. Bison'' must be approved for accuracy by the Foundation.
  25.  
  26.  
  27. 
  28. File: bison.info,  Node: Mfcalc Decl,  Next: Mfcalc Rules,  Prev: Multi-function Calc,  Up: Multi-function Calc
  29.  
  30. Declarations for `mfcalc'
  31. -------------------------
  32.  
  33. Here are the C and Bison declarations for the multi-function
  34. calculator.
  35.  
  36.      %{
  37.      #include <math.h>  /* For math functions, cos(), sin(), etc      */
  38.      #include "calc.h"  /* Contains definition of `symrec' */
  39.      %}
  40.      %union {
  41.      double     val;  /* For returning numbers.              */
  42.      symrec  *tptr;   /* For returning symbol-table pointers */
  43.      }
  44.      
  45.      %token <val>  NUM        /* Simple double precision number  */
  46.      %token <tptr> VAR FNCT   /* Variable and Function           */
  47.      %type  <val>  exp
  48.      
  49.      %right '='
  50.      %left '-' '+'
  51.      %left '*' '/'
  52.      %left NEG     /* Negation--unary minus */
  53.      %right '^'    /* Exponentiation        */
  54.      
  55.      /* Grammar follows */
  56.      
  57.      %%
  58.  
  59. The above grammar introduces only two new features of the Bison
  60. language.  These features allow semantic values to have various data
  61. types (*note Multiple Types::.).
  62.  
  63. The `%union' declaration specifies the entire list of possible types;
  64. this is instead of defining `YYSTYPE'.  The allowable types are now
  65. double-floats (for `exp' and `NUM') and pointers to entries in the
  66. symbol table.  *Note Union Decl::.
  67.  
  68. Since values can now have various types, it is necessary to associate
  69. a type with each grammar symbol whose semantic value is used.  These
  70. symbols are `NUM', `VAR', `FNCT', and `exp'.  Their declarations are
  71. augmented with information about their data type (placed between
  72. angle brackets).
  73.  
  74. The Bison construct `%type' is used for declaring nonterminal
  75. symbols, just as `%token' is used for declaring token types.  We have
  76. not used `%type' before because nonterminal symbols are normally
  77. declared implicitly by the rules that define them.  But `exp' must be
  78. declared explicitly so we can specify its value type.  *Note Type
  79. Decl::.
  80.  
  81.  
  82. 
  83. File: bison.info,  Node: Mfcalc Rules,  Next: Mfcalc Symtab,  Prev: Mfcalc Decl,  Up: Multi-function Calc
  84.  
  85. Grammar Rules for `mfcalc'
  86. --------------------------
  87.  
  88. Here are the grammar rules for the multi-function calculator.  Most
  89. of them are copied directly from `calc'; three rules, those which
  90. mention `VAR' or `FNCT', are new.
  91.  
  92.      input:   /* empty */
  93.              | input line
  94.      ;
  95.      
  96.      line:
  97.                '\n'
  98.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  99.              | error '\n' { yyerrok;                  }
  100.      ;
  101.      
  102.      exp:      NUM                { $$ = $1;                         }
  103.              | VAR                { $$ = $1->value.var;              }
  104.              | VAR '=' exp        { $$ = $3; $1->value.var = $3;     }
  105.              | FNCT '(' exp ')'   { $$ = (*($1->value.fnctptr))($3); }
  106.              | exp '+' exp        { $$ = $1 + $3;                    }
  107.              | exp '-' exp        { $$ = $1 - $3;                    }
  108.              | exp '*' exp        { $$ = $1 * $3;                    }
  109.              | exp '/' exp        { $$ = $1 / $3;                    }
  110.              | '-' exp  %prec NEG { $$ = -$2;                        }
  111.              | exp '^' exp        { $$ = pow ($1, $3);               }
  112.              | '(' exp ')'        { $$ = $2;                         }
  113.      ;
  114.      /* End of grammar */
  115.      %%
  116.  
  117.  
  118. 
  119. File: bison.info,  Node: Mfcalc Symtab,  Prev: Mfcalc Rules,  Up: Multi-function Calc
  120.  
  121. Managing the Symbol Table for `mfcalc'
  122. --------------------------------------
  123.  
  124. The multi-function calculator requires a symbol table to keep track
  125. of the names and meanings of variables and functions.  This doesn't
  126. affect the grammar rules (except for the actions) or the Bison
  127. declarations, but it requires some additional C functions for support.
  128.  
  129. The symbol table itself consists of a linked list of records.  Its
  130. definition, which is kept in the header `calc.h', is as follows.  It
  131. provides for either functions or variables to be placed in the table.
  132.  
  133.      /* Data type for links in the chain of symbols.  */
  134.      struct symrec
  135.      {
  136.        char *name;  /* name of symbol              */
  137.        int type;    /* type of symbol: either VAR or FNCT */
  138.        union {
  139.          double var;           /* value of a VAR  */
  140.          double (*fnctptr)();  /* value of a FNCT */
  141.        } value;
  142.        struct symrec *next;    /* link field    */
  143.      };
  144.      
  145.      typedef struct symrec symrec;
  146.      
  147.      /* The symbol table: a chain of `struct symrec'.  */
  148.      extern symrec *sym_table;
  149.      
  150.      symrec *putsym ();
  151.      symrec *getsym ();
  152.  
  153. The new version of `main' includes a call to `init_table', a function
  154. that initializes the symbol table.  Here it is, and `init_table' as
  155. well:
  156.  
  157.      #include <stdio.h>
  158.      
  159.      main()
  160.      {
  161.        init_table ();
  162.        yyparse ();
  163.      }
  164.      
  165.      yyerror (s)  /* Called by yyparse on error */
  166.           char *s;
  167.      {
  168.        printf ("%s\n", s);
  169.      }
  170.      
  171.      struct init
  172.      {
  173.        char *fname;
  174.        double (*fnct)();
  175.      };
  176.      
  177.      struct init arith_fncts[]
  178.        = {
  179.            "sin", sin,
  180.            "cos", cos,
  181.            "atan", atan,
  182.            "ln", log,
  183.            "exp", exp,
  184.            "sqrt", sqrt,
  185.            0, 0
  186.          };
  187.      
  188.      /* The symbol table: a chain of `struct symrec'.  */
  189.      symrec *sym_table = (symrec *)0;
  190.      
  191.      init_table ()  /* puts arithmetic functions in table. */
  192.      {
  193.        int i;
  194.        symrec *ptr;
  195.        for (i = 0; arith_fncts[i].fname != 0; i++)
  196.          {
  197.            ptr = putsym (arith_fncts[i].fname, FNCT);
  198.            ptr->value.fnctptr = arith_fncts[i].fnct;
  199.          }
  200.      }
  201.  
  202. By simply editing the initialization list and adding the necessary
  203. include files, you can add additional functions to the calculator.
  204.  
  205. Two important functions allow look-up and installation of symbols in
  206. the symbol table.  The function `putsym' is passed a name and the
  207. type (`VAR' or `FNCT') of the object to be installed.  The object is
  208. linked to the front of the list, and a pointer to the object is
  209. returned.  The function `getsym' is passed the name of the symbol to
  210. look up.  If found, a pointer to that symbol is returned; otherwise
  211. zero is returned.
  212.  
  213.      symrec *
  214.      putsym (sym_name,sym_type)
  215.           char *sym_name;
  216.           int sym_type;
  217.      {
  218.        symrec *ptr;
  219.        ptr = (symrec *) malloc (sizeof(symrec));
  220.        ptr->name = (char *) malloc (strlen(sym_name)+1);
  221.        strcpy (ptr->name,sym_name);
  222.        ptr->type = sym_type;
  223.        ptr->value.var = 0; /* set value to 0 even if fctn.  */
  224.        ptr->next = (struct symrec *)sym_table;
  225.        sym_table = ptr;
  226.        return ptr;
  227.      }
  228.      
  229.      symrec *
  230.      getsym (sym_name)
  231.           char *sym_name;
  232.      {
  233.        symrec *ptr;
  234.        for (ptr = sym_table; ptr != (symrec *) 0;
  235.             ptr = (symrec *)ptr->next)
  236.          if (strcmp (ptr->name,sym_name) == 0)
  237.            return ptr;
  238.        return 0;
  239.      }
  240.  
  241. The function `yylex' must now recognize variables, numeric values,
  242. and the single-character arithmetic operators.  Strings of
  243. alphanumeric characters with a leading nondigit are recognized as
  244. either variables or functions depending on what the symbol table says
  245. about them.
  246.  
  247. The string is passed to `getsym' for look up in the symbol table.  If
  248. the name appears in the table, a pointer to its location and its type
  249. (`VAR' or `FNCT') is returned to `yyparse'.  If it is not already in
  250. the table, then it is installed as a `VAR' using `putsym'.  Again, a
  251. pointer and its type (which must be `VAR') is returned to `yyparse'.
  252.  
  253. No change is needed in the handling of numeric values and arithmetic
  254. operators in `yylex'.
  255.  
  256.      #include <ctype.h>
  257.      yylex()
  258.      {
  259.        int c;
  260.      
  261.        /* Ignore whitespace, get first nonwhite character.  */
  262.        while ((c = getchar ()) == ' ' || c == '\t');
  263.      
  264.        if (c == EOF)
  265.          return 0;
  266.      
  267.        /* Char starts a number => parse the number.  */
  268.        if (c == '.' || isdigit (c))
  269.          {
  270.            ungetc (c, stdin);
  271.            scanf ("%lf", &yylval.val);
  272.            return NUM;
  273.          }
  274.      
  275.        /* Char starts an identifier => read the name.  */
  276.        if (isalpha (c))
  277.          {
  278.            symrec *s;
  279.            static char *symbuf = 0;
  280.            static int length = 0;
  281.            int i;
  282.      
  283.            /* Initially make the buffer long enough
  284.               for a 40-character symbol name.  */
  285.            if (length == 0)
  286.              length = 40, symbuf = (char *)malloc (length + 1);
  287.      
  288.            i = 0;
  289.            do
  290.              {
  291.                /* If buffer is full, make it bigger.  */
  292.                if (i == length)
  293.                  {
  294.                    length *= 2;
  295.                    symbuf = (char *)realloc (symbuf, length + 1);
  296.                  }
  297.                /* Add this character to the buffer.  */
  298.                symbuf[i++] = c;
  299.                /* Get another character.  */
  300.                c = getchar ();
  301.              }
  302.            while (c != EOF && isalnum (c));
  303.      
  304.            ungetc (c, stdin);
  305.            symbuf[i] = '\0';
  306.      
  307.            s = getsym (symbuf);
  308.            if (s == 0)
  309.              s = putsym (symbuf, VAR);
  310.            yylval.tptr = s;
  311.            return s->type;
  312.          }
  313.      
  314.        /* Any other character is a token by itself.  */
  315.        return c;
  316.      }
  317.  
  318. This program is both powerful and flexible. You may easily add new
  319. functions, and it is a simple job to modify this code to install
  320. predefined variables such as `pi' or `e' as well.
  321.  
  322.  
  323. 
  324. File: bison.info,  Node: Exercises,  Prev: Multi-function calc,  Up: Examples
  325.  
  326. Exercises
  327. =========
  328.  
  329.   1. Add some new functions from `math.h' to the initialization list.
  330.  
  331.   2. Add another array that contains constants and their values. 
  332.      Then modify `init_table' to add these constants to the symbol
  333.      table.  It will be easiest to give the constants type `VAR'.
  334.  
  335.   3. Make the program report an error if the user refers to an
  336.      uninitialized variable in any way except to store a value in it.
  337.  
  338.  
  339. 
  340. File: bison.info,  Node: Grammar File,  Next: Interface,  Prev: Examples,  Up: Top
  341.  
  342. Bison Grammar Files
  343. *******************
  344.  
  345. Bison takes as input a context-free grammar specification and
  346. produces a C-language function that recognizes correct instances of
  347. the grammar.
  348.  
  349. The Bison grammar input file conventionally has a name ending in `.y'.
  350.  
  351. * Menu:
  352.  
  353. * Grammar Outline::    Overall layout of the grammar file.
  354. * Symbols::            Terminal and nonterminal symbols.
  355. * Rules::              How to write grammar rules.
  356. * Recursion::           Writing recursive rules.
  357. * Semantics::          Semantic values and actions.
  358. * Declarations::       All kinds of Bison declarations are described here.
  359.  
  360.  
  361. 
  362. File: bison.info,  Node: Grammar Outline,  Next: Symbols,  Prev: Grammar File,  Up: Grammar File
  363.  
  364. Outline of a Bison Grammar
  365. ==========================
  366.  
  367. A Bison grammar file has four main sections, shown here with the
  368. appropriate delimiters:
  369.  
  370.      %{
  371.      C DECLARATIONS
  372.      %}
  373.      
  374.      BISON DECLARATIONS
  375.      
  376.      %%
  377.      GRAMMAR RULES
  378.      %%
  379.      
  380.      ADDITIONAL C CODE
  381.  
  382. Comments enclosed in `/* ... */' may appear in any of the sections.
  383.  
  384. * Menu:
  385.  
  386. * C Declarations::      Syntax and usage of the C declarations section.
  387. * Bison Declarations::  Syntax and usage of the Bison declarations section.
  388. * Grammar Rules::       Syntax and usage of the grammar rules section.
  389. * C Code::              Syntax and usage of the additional C code section.
  390.  
  391.  
  392. 
  393. File: bison.info,  Node: C Declarations,  Next: Bison Declarations,  Prev: Grammar Outline,  Up: Grammar Outline
  394.  
  395. The C Declarations Section
  396. --------------------------
  397.  
  398. The C DECLARATIONS section contains macro definitions and
  399. declarations of functions and variables that are used in the actions
  400. in the grammar rules.  These are copied to the beginning of the
  401. parser file so that they precede the definition of `yylex'.  You can
  402. use `#include' to get the declarations from a header file.  If you
  403. don't need any C declarations, you may omit the `%{' and `%}'
  404. delimiters that bracket this section.
  405.  
  406.  
  407. 
  408. File: bison.info,  Node: Bison Declarations,  Next: Grammar Rules,  Prev: C Declarations,  Up: Grammar Outline
  409.  
  410. The Bison Declarations Section
  411. ------------------------------
  412.  
  413. The BISON DECLARATIONS section contains declarations that define
  414. terminal and nonterminal symbols, specify precedence, and so on.  In
  415. some simple grammars you may not need any declarations.  *Note
  416. Declarations::.
  417.  
  418.  
  419. 
  420. File: bison.info,  Node: Grammar Rules,  Next: C Code,  Prev: Bison Declarations,  Up: Grammar Outline
  421.  
  422. The Grammar Rules Section
  423. -------------------------
  424.  
  425. The "grammar rules" section contains one or more Bison grammar rules,
  426. and nothing else.  *Note Rules::.
  427.  
  428. There must always be at least one grammar rule, and the first `%%'
  429. (which precedes the grammar rules) may never be omitted even if it is
  430. the first thing in the file.
  431.  
  432.  
  433. 
  434. File: bison.info,  Node: C Code,  Prev: Grammar Rules,  Up: Grammar Outline
  435.  
  436. The Additional C Code Section
  437. -----------------------------
  438.  
  439. The ADDITIONAL C CODE section is copied verbatim to the end of the
  440. parser file, just as the C DECLARATIONS section is copied to the
  441. beginning.  This is the most convenient place to put anything that
  442. you want to have in the parser file but which need not come before
  443. the definition of `yylex'.  For example, the definitions of `yylex'
  444. and `yyerror' often go here.  *Note Interface::.
  445.  
  446. If the last section is empty, you may omit the `%%' that separates it
  447. from the grammar rules.
  448.  
  449. The Bison parser itself contains many static variables whose names
  450. start with `yy' and many macros whose names start with `YY'.  It is a
  451. good idea to avoid using any such names (except those documented in
  452. this manual) in the additional C code section of the grammar file.
  453.  
  454.  
  455. 
  456. File: bison.info,  Node: Symbols,  Next: Rules,  Prev: Grammar Outline,  Up: Grammar File
  457.  
  458. Symbols, Terminal and Nonterminal
  459. =================================
  460.  
  461. "Symbols" in Bison grammars represent the grammatical classifications
  462. of the language.
  463.  
  464. A "terminal symbol" (also known as a "token type") represents a class
  465. of syntactically equivalent tokens.  You use the symbol in grammar
  466. rules to mean that a token in that class is allowed.  The symbol is
  467. represented in the Bison parser by a numeric code, and the `yylex'
  468. function returns a token type code to indicate what kind of token has
  469. been read.  You don't need to know what the code value is; you can
  470. use the symbol to stand for it.
  471.  
  472. A "nonterminal symbol" stands for a class of syntactically equivalent
  473. groupings.  The symbol name is used in writing grammar rules.  By
  474. convention, it should be all lower case.
  475.  
  476. Symbol names can contain letters, digits (not at the beginning),
  477. underscores and periods.  Periods make sense only in nonterminals.
  478.  
  479. There are two ways of writing terminal symbols in the grammar:
  480.  
  481.    * A "named token type" is written with an identifier, like an
  482.      identifier in C.  By convention, it should be all upper case. 
  483.      Each such name must be defined with a Bison declaration such as
  484.      `%token'.  *Note Token Decl::.
  485.  
  486.    * A "character token type" (or "literal token") is written in the
  487.      grammar using the same syntax used in C for character constants;
  488.      for example, `'+'' is a character token type.  A character token
  489.      type doesn't need to be declared unless you need to specify its
  490.      semantic value data type (*note Value Type::.), associativity,
  491.      or precedence (*note Precedence::.).
  492.  
  493.      By convention, a character token type is used only to represent
  494.      a token that consists of that particular character.  Thus, the
  495.      token type `'+'' is used to represent the character `+' as a
  496.      token.  Nothing enforces this convention, but if you depart from
  497.      it, your program will confuse other readers.
  498.  
  499.      All the usual escape sequences used in character literals in C
  500.      can be used in Bison as well, but you must not use the null
  501.      character as a character literal because its ASCII code, zero,
  502.      is the code `yylex' returns for end-of-input (*note Lexical::.).
  503.  
  504. How you choose to write a terminal symbol has no effect on its
  505. grammatical meaning.  That depends only on where it appears in rules
  506. and on when the parser function returns that symbol.
  507.  
  508. The value returned by `yylex' is always one of the terminal symbols
  509. (or 0 for end-of-input).  Whichever way you write the token type in
  510. the grammar rules, you write it the same way in the definition of
  511. `yylex'.  The numeric code for a character token type is simply the
  512. ASCII code for the character, so `yylex' can use the identical
  513. character constant to generate the requisite code.  Each named token
  514. type becomes a C macro in the parser file, so `yylex' can use the
  515. name to stand for the code.  (This is why periods don't make sense in
  516. terminal symbols.)  *Note Lexical::.
  517.  
  518. If `yylex' is defined in a separate file, you need to arrange for the
  519. token-type macro definitions to be available there.  Use the `-d'
  520. option when you run Bison, so that it will write these macro
  521. definitions into a separate header file `NAME.tab.h' which you can
  522. include in the other source files that need it.  *Note Invocation::.
  523.  
  524. The symbol `error' is a terminal symbol reserved for error recovery
  525. (*note Error Recovery::.); you shouldn't use it for any other purpose.
  526. In particular, `yylex' should never return this value.
  527.  
  528.  
  529. 
  530. File: bison.info,  Node: Rules,  Next: Recursion,  Prev: Symbols,  Up: Grammar File
  531.  
  532. Syntax of Grammar Rules
  533. =======================
  534.  
  535. A Bison grammar rule has the following general form:
  536.  
  537.      RESULT: COMPONENTS...
  538.              ;
  539.  
  540. where RESULT is the nonterminal symbol that this rule describes and
  541. COMPONENTS are various terminal and nonterminal symbols that are put
  542. together by this rule (*note Symbols::.).  For example,
  543.  
  544.      exp:      exp '+' exp
  545.              ;
  546.  
  547. says that two groupings of type `exp', with a `+' token in between,
  548. can be combined into a larger grouping of type `exp'.
  549.  
  550. Whitespace in rules is significant only to separate symbols.  You can
  551. add extra whitespace as you wish.
  552.  
  553. Scattered among the components can be ACTIONS that determine the
  554. semantics of the rule.  An action looks like this:
  555.  
  556.      {C STATEMENTS}
  557.  
  558. Usually there is only one action and it follows the components. 
  559. *Note Actions::.
  560.  
  561. Multiple rules for the same RESULT can be written separately or can
  562. be joined with the vertical-bar character `|' as follows:
  563.  
  564.      RESULT:   RULE1-COMPONENTS...
  565.              | RULE2-COMPONENTS...
  566.              ...
  567.              ;
  568.  
  569. They are still considered distinct rules even when joined in this way.
  570.  
  571. If COMPONENTS in a rule is empty, it means that RESULT can match the
  572. empty string.  For example, here is how to define a comma-separated
  573. sequence of zero or more `exp' groupings:
  574.  
  575.      expseq:   /* empty */
  576.              | expseq1
  577.              ;
  578.      
  579.      expseq1:  exp
  580.              | expseq1 ',' exp
  581.              ;
  582.  
  583. It is customary to write a comment `/* empty */' in each rule with no
  584. components.
  585.  
  586.  
  587. 
  588. File: bison.info,  Node: Recursion,  Next: Semantics,  Prev: Rules,  Up: Grammar File
  589.  
  590. Recursive Rules
  591. ===============
  592.  
  593. A rule is called "recursive" when its RESULT nonterminal appears also
  594. on its right hand side.  Nearly all Bison grammars need to use
  595. recursion, because that is the only way to define a sequence of any
  596. number of somethings.  Consider this recursive definition of a
  597. comma-separated sequence of one or more expressions:
  598.  
  599.      expseq1:  exp
  600.              | expseq1 ',' exp
  601.              ;
  602.  
  603. Since the recursive use of `expseq1' is the leftmost symbol in the
  604. right hand side, we call this "left recursion".  By contrast, here
  605. the same construct is defined using "right recursion":
  606.  
  607.      expseq1:  exp
  608.              | exp ',' expseq1
  609.              ;
  610.  
  611. Any kind of sequence can be defined using either left recursion or
  612. right recursion, but you should always use left recursion, because it
  613. can parse a sequence of any number of elements with bounded stack
  614. space.  Right recursion uses up space on the Bison stack in
  615. proportion to the number of elements in the sequence, because all the
  616. elements must be shifted onto the stack before the rule can be
  617. applied even once.  *Note Algorithm::, for further explanation of this.
  618.  
  619. "Indirect" or "mutual" recursion occurs when the result of the rule
  620. does not appear directly on its right hand side, but does appear in
  621. rules for other nonterminals which do appear on its right hand side. 
  622. For example:
  623.  
  624.      expr:     primary
  625.              | primary '+' primary
  626.              ;
  627.      
  628.      primary:  constant
  629.              | '(' expr ')'
  630.              ;
  631.  
  632. defines two mutually-recursive nonterminals, since each refers to the
  633. other.
  634.  
  635.  
  636. 
  637. File: bison.info,  Node: Semantics,  Next: Declarations,  Prev: Recursion,  Up: Grammar File
  638.  
  639. The Semantics of the Language
  640. =============================
  641.  
  642. The grammar rules for a language determine only the syntax.  The
  643. semantics are determined by the semantic values associated with
  644. various tokens and groupings, and by the actions taken when various
  645. groupings are recognized.
  646.  
  647. For example, the calculator calculates properly because the value
  648. associated with each expression is the proper number; it adds
  649. properly because the action for the grouping `X + Y' is to add the
  650. numbers associated with X and Y.
  651.  
  652. * Menu:
  653.  
  654. * Value Type::       Specifying one data type for all semantic values.
  655. * Multiple Types::   Specifying several alternative data types.
  656. * Actions::          An action is the semantic definition of a grammar rule.
  657. * Action Types::     Specifying data types for actions to operate on.
  658. * Mid-Rule Actions:: Most actions go at the end of a rule.
  659.                       This says when, why and how to use the exceptional
  660.                       action in the middle of a rule.
  661.  
  662.  
  663. 
  664. File: bison.info,  Node: Value Type,  Next: Multiple Types,  Prev: Semantics,  Up: Semantics
  665.  
  666. The Data Types of Semantic Values
  667. ---------------------------------
  668.  
  669. In a simple program it may be sufficient to use the same data type
  670. for the semantic values of all language constructs.  This was true in
  671. the RPN and infix calculator examples (*note RPN Calc::.).
  672.  
  673. Bison's default is to use type `int' for all semantic values.  To
  674. specify some other type, define `YYSTYPE' as a macro, like this:
  675.  
  676.      #define YYSTYPE double
  677.  
  678. This macro definition must go in the C declarations section of the
  679. grammar file (*note Grammar Outline::.).
  680.  
  681.  
  682. 
  683. File: bison.info,  Node: Multiple Types,  Next: Actions,  Prev: Value Type
  684.  
  685. More Than One Type for Semantic Values
  686. --------------------------------------
  687.  
  688. In most programs, you will need different data types for different
  689. kinds of tokens and groupings.  For example, a numeric constant may
  690. need type `int' or `long', while a string constant needs type `char
  691. *', and an identifier might need a pointer to an entry in the symbol
  692. table.
  693.  
  694. To use more than one data type for semantic values in one parser,
  695. Bison requires you to do two things:
  696.  
  697.    * Specify the entire collection of possible data types, with the
  698.      `%union' Bison declaration (*note Union Decl::.).
  699.  
  700.    * Choose one of those types for each symbol (terminal or
  701.      nonterminal) for which semantic values are used.  This is done
  702.      for tokens with the `%token' Bison declaration (*note Token
  703.      Decl::.) and for groupings with the `%type' Bison declaration
  704.      (*note Type Decl::.).
  705.  
  706.  
  707. 
  708. File: bison.info,  Node: Actions,  Next: Action Types,  Prev: Multiple Types,  Up: Semantics
  709.  
  710. Actions
  711. -------
  712.  
  713. An action accompanies a syntactic rule and contains C code to be
  714. executed each time an instance of that rule is recognized.  The task
  715. of most actions is to compute a semantic value for the grouping built
  716. by the rule from the semantic values associated with tokens or
  717. smaller groupings.
  718.  
  719. An action consists of C statements surrounded by braces, much like a
  720. compound statement in C.  It can be placed at any position in the
  721. rule; it is executed at that position.  Most rules have just one
  722. action at the end of the rule, following all the components.  Actions
  723. in the middle of a rule are tricky and used only for special purposes
  724. (*note Mid-Rule Actions::.).
  725.  
  726. The C code in an action can refer to the semantic values of the
  727. components matched by the rule with the construct `$N', which stands
  728. for the value of the Nth component.  The semantic value for the
  729. grouping being constructed is `$$'.  (Bison translates both of these
  730. constructs into array element references when it copies the actions
  731. into the parser file.)
  732.  
  733. Here is a typical example:
  734.  
  735.      exp:    ...
  736.              | exp '+' exp
  737.                  { $$ = $1 + $3; }
  738.  
  739. This rule constructs an `exp' from two smaller `exp' groupings
  740. connected by a plus-sign token.  In the action, `$1' and `$3' refer
  741. to the semantic values of the two component `exp' groupings, which
  742. are the first and third symbols on the right hand side of the rule. 
  743. The sum is stored into `$$' so that it becomes the semantic value of
  744. the addition-expression just recognized by the rule.  If there were a
  745. useful semantic value associated with the `+' token, it could be
  746. referred to as `$2'.
  747.  
  748. `$N' with N zero or negative is allowed for reference to tokens and
  749. groupings on the stack *before* those that match the current rule. 
  750. This is a very risky practice, and to use it reliably you must be
  751. certain of the context in which the rule is applied.  Here is a case
  752. in which you can use this reliably:
  753.  
  754.      foo:      expr bar '+' expr  { ... }
  755.              | expr bar '-' expr  { ... }
  756.              ;
  757.      
  758.      bar:      /* empty */
  759.              { previous_expr = $0; }
  760.              ;
  761.  
  762. As long as `bar' is used only in the fashion shown here, `$0' always
  763. refers to the `expr' which precedes `bar' in the definition of `foo'.
  764.  
  765.  
  766. 
  767. File: bison.info,  Node: Action Types,  Next: Mid-Rule Actions,  Prev: Actions,  Up: Semantics
  768.  
  769. Data Types of Values in Actions
  770. -------------------------------
  771.  
  772. If you have chosen a single data type for semantic values, the `$$'
  773. and `$N' constructs always have that data type.
  774.  
  775. If you have used `%union' to specify a variety of data types, then
  776. you must declare a choice among these types for each terminal or
  777. nonterminal symbol that can have a semantic value.  Then each time
  778. you use `$$' or `$N', its data type is determined by which symbol it
  779. refers to in the rule.  In this example,
  780.  
  781.      exp:    ...
  782.              | exp '+' exp
  783.                  { $$ = $1 + $3; }
  784.  
  785. `$3' and `$$' refer to instances of `exp', so they all have the data
  786. type declared for the nonterminal symbol `exp'.  If `$2' were used,
  787. it would have the data type declared for the terminal symbol `'+'',
  788. whatever that might be.
  789.  
  790. Alternatively, you can specify the data type when you refer to the
  791. value, by inserting `<TYPE>' after the `$' at the beginning of the
  792. reference.  For example, if you have defined types as shown here:
  793.  
  794.      %union {
  795.        int itype;
  796.        double dtype;
  797.      }
  798.  
  799. then you can write `$<itype>1' to refer to the first subunit of the
  800. rule as an integer, or `$<dtype>1' to refer to it as a double.
  801.  
  802.  
  803. 
  804. File: bison.info,  Node: Mid-Rule Actions,  Prev: Action Types,  Up: Semantics
  805.  
  806. Actions in Mid-Rule
  807. -------------------
  808.  
  809. Occasionally it is useful to put an action in the middle of a rule. 
  810. These actions are written just like usual end-of-rule actions, but
  811. they are executed before the parser even recognizes the following
  812. components.
  813.  
  814. A mid-rule action may refer to the components preceding it using
  815. `$N', but it may not refer to subsequent components because it is run
  816. before they are parsed.
  817.  
  818. The mid-rule action itself counts as one of the components of the rule.
  819. This makes a difference when there is another action later in the
  820. same rule (and usually there is another at the end): you have to
  821. count the actions along with the symbols when working out which
  822. number N to use in `$N'.
  823.  
  824. The mid-rule action can also have a semantic value.  This can be set
  825. within that action by an assignment to `$$', and can referred to by
  826. later actions using `$N'.  Since there is no symbol to name the
  827. action, there is no way to declare a data type for the value in
  828. advance, so you must use the `$<...>' construct to specify a data
  829. type each time you refer to this value.
  830.  
  831. Here is an example from a hypothetical compiler, handling a `let'
  832. statement that looks like `let (VARIABLE) STATEMENT' and serves to
  833. create a variable named VARIABLE temporarily for the duration of
  834. STATEMENT.  To parse this construct, we must put VARIABLE into the
  835. symbol table while STATEMENT is parsed, then remove it afterward. 
  836. Here is how it is done:
  837.  
  838.      stmt:   LET '(' var ')'
  839.                      { $<context>$ = push_context ();
  840.                        declare_variable ($3); }
  841.              stmt    { $$ = $6;
  842.                        pop_context ($<context>5); }
  843.  
  844. As soon as `let (VARIABLE)' has been recognized, the first action is
  845. run.  It saves a copy of the current semantic context (the list of
  846. accessible variables) as its semantic value, using alternative
  847. `context' in the data-type union.  Then it calls `declare_variable'
  848. to add the new variable to that list.  Once the first action is
  849. finished, the embedded statement `stmt' can be parsed.  Note that the
  850. mid-rule action is component number 5, so the `stmt' is component
  851. number 6.
  852.  
  853. After the embedded statement is parsed, its semantic value becomes
  854. the value of the entire `let'-statement.  Then the semantic value
  855. from the earlier action is used to restore the prior list of
  856. variables.  This removes the temporary `let'-variable from the list
  857. so that it won't appear to exist while the rest of the program is
  858. parsed.
  859.  
  860. Taking action before a rule is completely recognized often leads to
  861. conflicts since the parser must commit to a parse in order to execute
  862. the action.  For example, the following two rules, without mid-rule
  863. actions, can coexist in a working parser because the parser can shift
  864. the open-brace token and look at what follows before deciding whether
  865. there is a declaration or not:
  866.  
  867.      compound: '{' declarations statements '}'
  868.              | '{' statements '}'
  869.              ;
  870.  
  871. But when we add a mid-rule action as follows, the rules become
  872. nonfunctional:
  873.  
  874.      compound: { prepare_for_local_variables (); }
  875.                '{' declarations statements '}'
  876.  
  877.              | '{' statements '}'
  878.              ;
  879.  
  880. Now the parser is forced to decide whether to run the mid-rule action
  881. when it has read no farther than the open-brace.  In other words, it
  882. must commit to using one rule or the other, without sufficient
  883. information to do it correctly.  (The open-brace token is what is
  884. called the "look-ahead" token at this time, since the parser is still
  885. deciding what to do about it.  *Note Look-Ahead::.)
  886.  
  887. You might think that you could correct the problem by putting
  888. identical actions into the two rules, like this:
  889.  
  890.      compound: { prepare_for_local_variables (); }
  891.                '{' declarations statements '}'
  892.              | { prepare_for_local_variables (); }
  893.                '{' statements '}'
  894.              ;
  895.  
  896. But this does not help, because Bison does not realize that the two
  897. actions are identical.  (Bison never tries to understand the C code
  898. in an action.)
  899.  
  900. If the grammar is such that a declaration can be distinguished from a
  901. statement by the first token (which is true in C), then one solution
  902. which does work is to put the action after the open-brace, like this:
  903.  
  904.      compound: '{' { prepare_for_local_variables (); }
  905.                declarations statements '}'
  906.              | '{' statements '}'
  907.              ;
  908.  
  909. Now the first token of the following declaration or statement, which
  910. would in any case tell Bison which rule to use, can still do so.
  911.  
  912. Another solution is to bury the action inside a nonterminal symbol
  913. which serves as a subroutine:
  914.  
  915.      subroutine: /* empty */
  916.                { prepare_for_local_variables (); }
  917.              ;
  918.      
  919.      compound: subroutine
  920.                '{' declarations statements '}'
  921.              | subroutine
  922.                '{' statements '}'
  923.              ;
  924.  
  925. Now Bison can execute the action in the rule for `subroutine' without
  926. deciding which rule for `compound' it will eventually use.  Note that
  927. the action is now at the end of its rule.  Any mid-rule action can be
  928. converted to an end-of-rule action in this way, and this is what
  929. Bison actually does to implement mid-rule actions.
  930.  
  931.  
  932. 
  933. File: bison.info,  Node: Declarations,  Prev: Semantics,  Up: Grammar File
  934.  
  935. Bison Declarations
  936. ==================
  937.  
  938. The "Bison declarations" section of a Bison grammar defines the
  939. symbols used in formulating the grammar and the data types of
  940. semantic values.  *Note Symbols::.
  941.  
  942. All token type names (but not single-character literal tokens such as
  943. `'+'' and `'*'') must be declared.  Nonterminal symbols must be
  944. declared if you need to specify which data type to use for the
  945. semantic value (*note Multiple Types::.).
  946.  
  947. The first rule in the file also specifies the start symbol, by default.
  948. If you want some other symbol to be the start symbol, you must
  949. declare it explicitly (*note Language and Grammar::.).
  950.  
  951. * Menu:
  952.  
  953. * Token Decl::       Declaring terminal symbols.
  954. * Precedence Decl::  Declaring terminals with precedence and associativity.
  955. * Union Decl::       Declaring the set of all semantic value types.
  956. * Type Decl::        Declaring the choice of type for a nonterminal symbol.
  957. * Expect Decl::      Suppressing warnings about shift/reduce conflicts.
  958. * Start Decl::       Specifying the start symbol.
  959. * Pure Decl::        Requesting a reentrant parser.
  960. * Decl Summary::     Table of all Bison declarations.
  961.  
  962.  
  963. 
  964. File: bison.info,  Node: Token Decl,  Next: Precedence Decl,  Prev: Declarations,  Up: Declarations
  965.  
  966. Declaring Token Type Names
  967. --------------------------
  968.  
  969. The basic way to declare a token type name (terminal symbol) is as
  970. follows:
  971.  
  972.      %token NAME
  973.  
  974. Bison will convert this into a `#define' directive in the parser, so
  975. that the function `yylex' (if it is in this file) can use the name
  976. NAME to stand for this token type's code.
  977.  
  978. Alternatively you can use `%left', `%right', or `%nonassoc' instead
  979. of `%token', if you wish to specify precedence.  *Note Precedence
  980. Decl::.
  981.  
  982. You can explicitly specify the numeric code for a token type by
  983. appending an integer value in the field immediately following the
  984. token name:
  985.  
  986.      %token NUM 300
  987.  
  988. It is generally best, however, to let Bison choose the numeric codes
  989. for all token types.  Bison will automatically select codes that
  990. don't conflict with each other or with ASCII characters.
  991.  
  992. In the event that the stack type is a union, you must augment the
  993. `%token' or other token declaration to include the data type
  994. alternative delimited by angle-brackets (*note Multiple Types::.). 
  995. For example:
  996.  
  997.      %union {              /* define stack type */
  998.        double val;
  999.        symrec *tptr;
  1000.      }
  1001.      %token <val> NUM      /* define token NUM and its type */
  1002.  
  1003.  
  1004. 
  1005. File: bison.info,  Node: Precedence Decl,  Next: Token Decl,  Prev: Union Decl,  Up: Declarations
  1006.  
  1007. Declaring Operator Precedence
  1008. -----------------------------
  1009.  
  1010. Use the `%left', `%right' or `%nonassoc' declaration to declare a
  1011. token and specify its precedence and associativity, all at once. 
  1012. These are called "precedence declarations".  *Note Precedence::, for
  1013. general information on operator precedence.
  1014.  
  1015. The syntax of a precedence declaration is the same as that of
  1016. `%token': either
  1017.  
  1018.      %left SYMBOLS...
  1019.  
  1020.  or
  1021.  
  1022.      %left <TYPE> SYMBOLS...
  1023.  
  1024.  And indeed any of these declarations serves the purposes of `%token'.
  1025. But in addition, they specify the associativity and relative
  1026. precedence for all the SYMBOLS:
  1027.  
  1028.    * The associativity of an operator OP determines how repeated uses
  1029.      of the operator nest: whether `X OP Y OP Z' is parsed by
  1030.      grouping X with Y first or by grouping Y with Z first.  `%left'
  1031.      specifies left-associativity (grouping X with Y first) and
  1032.      `%right' specifies right-associativity (grouping Y with Z
  1033.      first).  `%nonassoc' specifies no associativity, which means
  1034.      that `X OP Y OP Z' is considered a syntax error.
  1035.  
  1036.    * The precedence of an operator determines how it nests with other
  1037.      operators.  All the tokens declared in a single precedence
  1038.      declaration have equal precedence and nest together according to
  1039.      their associativity.  When two tokens declared in different
  1040.      precedence declarations associate, the one declared later has
  1041.      the higher precedence and is grouped first.
  1042.  
  1043.  
  1044. 
  1045. File: bison.info,  Node: Union Decl,  Next: Type Decl,  Prev: Precedence Decl,  Up: Declarations
  1046.  
  1047. Declaring the Collection of Value Types
  1048. ---------------------------------------
  1049.  
  1050. The `%union' declaration specifies the entire collection of possible
  1051. data types for semantic values.  The keyword `%union' is followed by
  1052. a pair of braces containing the same thing that goes inside a `union'
  1053. in C.  For example:
  1054.  
  1055.      %union {
  1056.        double val;
  1057.        symrec *tptr;
  1058.      }
  1059.  
  1060. This says that the two alternative types are `double' and `symrec *'.
  1061. They are given names `val' and `tptr'; these names are used in the
  1062. `%token' and `%type' declarations to pick one of the types for a
  1063. terminal or nonterminal symbol (*note Type Decl::.).
  1064.  
  1065. Note that, unlike making a `union' declaration in C, you do not write
  1066. a semicolon after the closing brace.
  1067.  
  1068.  
  1069. 
  1070. File: bison.info,  Node: Type Decl,  Next: Expect Decl,  Prev: Union Decl,  Up: Declarations
  1071.  
  1072. Declaring Value Types of Nonterminal Symbols
  1073. --------------------------------------------
  1074.  
  1075. When you use `%union' to specify multiple value types, you must
  1076. declare the value type of each nonterminal symbol for which values
  1077. are used.  This is done with a `%type' declaration, like this:
  1078.  
  1079.      %type <TYPE> NONTERMINAL...
  1080.  
  1081.  Here NONTERMINAL is the name of a nonterminal symbol, and TYPE is the
  1082. name given in the `%union' to the alternative that you want (*note
  1083. Union Decl::.).  You can give any number of nonterminal symbols in
  1084. the same `%type' declaration, if they have the same value type.  Use
  1085. spaces to separate the symbol names.
  1086.  
  1087.  
  1088. 
  1089. File: bison.info,  Node: Expect Decl,  Next: Start Decl,  Prev: Type Decl,  Up: Declarations
  1090.  
  1091. Preventing Warnings about Conflicts
  1092. -----------------------------------
  1093.  
  1094. Bison normally warns if there are any conflicts in the grammar (*note
  1095. Shift/Reduce::.), but most real grammars have harmless shift/reduce
  1096. conflicts which are resolved in a predictable way and would be
  1097. difficult to eliminate.  It is desirable to suppress the warning
  1098. about these conflicts unless the number of conflicts changes.  You
  1099. can do this with the `%expect' declaration.
  1100.  
  1101. The declaration looks like this:
  1102.  
  1103.      %expect N
  1104.  
  1105. Here N is a decimal integer.  The declaration says there should be no
  1106. warning if there are N shift/reduce conflicts and no reduce/reduce
  1107. conflicts.  The usual warning is given if there are either more or
  1108. fewer conflicts, or if there are any reduce/reduce conflicts.
  1109.  
  1110. In general, using `%expect' involves these steps:
  1111.  
  1112.    * Compile your grammar without `%expect'.  Use the `-v' option to
  1113.      get a verbose list of where the conflicts occur.  Bison will
  1114.      also print the number of conflicts.
  1115.  
  1116.    * Check each of the conflicts to make sure that Bison's default
  1117.      resolution is what you really want.  If not, rewrite the grammar
  1118.      and go back to the beginning.
  1119.  
  1120.    * Add an `%expect' declaration, copying the number N from the
  1121.      number which Bison printed.
  1122.  
  1123. Now Bison will stop annoying you about the conflicts you have
  1124. checked, but it will warn you again if changes in the grammer result
  1125. in additional conflicts.
  1126.  
  1127.  
  1128. 
  1129. File: bison.info,  Node: Start Decl,  Next: Pure Decl,  Prev: Expect Decl,  Up: Declarations
  1130.  
  1131. Declaring the Start-Symbol
  1132. --------------------------
  1133.  
  1134. Bison assumes by default that the start symbol for the grammar is the
  1135. first nonterminal specified in the grammar specification section. 
  1136. The programmer may override this restriction with the `%start'
  1137. declaration as follows:
  1138.  
  1139.      %start SYMBOL
  1140.  
  1141.  
  1142. 
  1143. File: bison.info,  Node: Pure Decl,  Next: Decl Summary,  Prev: Start Decl,  Up: Declarations
  1144.  
  1145. Requesting a Pure (Reentrant) Parser
  1146. ------------------------------------
  1147.  
  1148. A reentrant program is one which does not alter in the course of
  1149. execution.  Reentrancy is important whenever asynchronous execution
  1150. is possible; for example, a nonreentrant program may not be safe to
  1151. call from a signal handler.  In systems with multiple threads of
  1152. control, a nonreentrant program must be called only within interlocks.
  1153.  
  1154. The Bison parser is not normally a reentrant program, because it uses
  1155. two statically allocated variables for communication with `yylex'. 
  1156. These variables are `yylval' and `yylloc'.
  1157.  
  1158. The Bison declaration `%pure_parser' says that you want the parser to
  1159. be reentrant.  It looks like this:
  1160.  
  1161.      %pure_parser
  1162.  
  1163. The effect is that the the two communication variables become
  1164. automatic variables in `yyparse', and a different calling convention
  1165. is used for the lexical analyzer function `yylex'.  The convention
  1166. for calling `yyparse' is unchanged.  *Note Lexical::, for the details
  1167. of this.
  1168.  
  1169.  
  1170. 
  1171. File: bison.info,  Node: Decl Summary,  Prev: Pure Decl,  Up: Declarations
  1172.  
  1173. Bison Declaration Summary
  1174. -------------------------
  1175.  
  1176. Here is a summary of all Bison declarations:
  1177.  
  1178. `%union'
  1179.      Declare the collection of data types that semantic values may
  1180.      have (*note Union Decl::.).
  1181.  
  1182. `%token'
  1183.      Declare a terminal symbol (token type name) with no precedence
  1184.      or associativity specified (*note Token Decl::.).
  1185.  
  1186. `%right'
  1187.      Declare a terminal symbol (token type name) that is
  1188.      right-associative (*note Precedence Decl::.).
  1189.  
  1190. `%left'
  1191.      Declare a terminal symbol (token type name) that is
  1192.      left-associative (*note Precedence Decl::.).
  1193.  
  1194. `%nonassoc'
  1195.      Declare a terminal symbol (token type name) that is
  1196.      nonassociative (using it in a way that would be associative is a
  1197.      syntax error) (*note Precedence Decl::.).
  1198.  
  1199. `%type'
  1200.      Declare the type of semantic values for a nonterminal symbol
  1201.      (*note Type Decl::.).
  1202.  
  1203. `%start'
  1204.      Specify the grammar's start symbol (*note Start Decl::.).
  1205.  
  1206. `%expect'
  1207.      Declare the expected number of shift-reduce conflicts (*note
  1208.      Expect Decl::.).
  1209.  
  1210. `%pure_parser'
  1211.      Request a pure (reentrant) parser program (*note Pure Decl::.).
  1212.  
  1213.  
  1214. 
  1215. File: bison.info,  Node: Interface,  Next: Algorithm,  Prev: Grammar File,  Up: Top
  1216.  
  1217. Parser C-Language Interface
  1218. ***************************
  1219.  
  1220. The Bison parser is actually a C function named `yyparse'.  Here we
  1221. describe the interface conventions of `yyparse' and the other
  1222. functions that it needs to use.
  1223.  
  1224. Keep in mind that the parser uses many C identifiers starting with
  1225. `yy' and `YY' for internal purposes.  If you use such an identifier
  1226. (aside from those in this manual) in an action or in additional C
  1227. code in the grammar file, you are likely to run into trouble.
  1228.  
  1229. * Menu:
  1230.  
  1231. * Parser Function:: How to call `yyparse' and what it returns.
  1232. * Lexical::         You must supply a function `yylex' which reads tokens.
  1233. * Error Reporting:: You must supply a function `yyerror'.
  1234. * Action Features:: Special features for use in actions.
  1235.  
  1236.  
  1237. 
  1238. File: bison.info,  Node: Parser Function,  Next: Lexical,  Prev: Interface,  Up: Interface
  1239.  
  1240. The Parser Function `yyparse'
  1241. =============================
  1242.  
  1243. You call the function `yyparse' to cause parsing to occur.  This
  1244. function reads tokens, executes actions, and ultimately returns when
  1245. it encounters end-of-input or an unrecoverable syntax error.  You can
  1246. also write an action which directs `yyparse' to return immediately
  1247. without reading further.
  1248.  
  1249. The value returned by `yyparse' is 0 if parsing was successful
  1250. (return is due to end-of-input).
  1251.  
  1252. The value is 1 if parsing failed (return is due to a syntax error).
  1253.  
  1254. In an action, you can cause immediate return from `yyparse' by using
  1255. these macros:
  1256.  
  1257. `YYACCEPT'
  1258.      Return immediately with value 0 (to report success).
  1259.  
  1260. `YYABORT'
  1261.      Return immediately with value 1 (to report failure).
  1262.  
  1263.  
  1264. 
  1265. File: bison.info,  Node: Lexical,  Next: Error Reporting,  Prev: Parser Function,  Up: Interface
  1266.  
  1267. The Lexical Analyzer Function `yylex'
  1268. =====================================
  1269.  
  1270. The "lexical analyzer" function, `yylex', recognizes tokens from the
  1271. input stream and returns them to the parser.  Bison does not create
  1272. this function automatically; you must write it so that `yyparse' can
  1273. call it.  The function is sometimes referred to as a lexical scanner.
  1274.  
  1275. The value that `yylex' returns must be the numeric code for the type
  1276. of token it has just found, or 0 for end-of-input.  *Note Symbols::.
  1277.  
  1278. When a token is referred to in the grammar rules by a name, that name
  1279. in the parser file becomes a C macro whose definition is the proper
  1280. numeric code for that token type.  So `yylex' can use the name to
  1281. indicate that type.
  1282.  
  1283. When a token is referred to in the grammar rules by a character
  1284. literal, the numeric code for that character is also the code for the
  1285. token type.  So `yylex' can simply return that character code.  The
  1286. null character must not be used this way, because its code is zero
  1287. and that is what signifies end-of-input.
  1288.  
  1289. Here is an example showing these things:
  1290.  
  1291.      yylex()
  1292.      {
  1293.        ...
  1294.        if (c == EOF)     /* Detect end of file.  */
  1295.          return 0;
  1296.        ...
  1297.        if (c == '+' || c == '-')
  1298.          return c;      /* Assume token type for `+' is '+'.  */
  1299.        ...
  1300.        return INT;      /* Return the type of the token.  */
  1301.        ...
  1302.      }
  1303.  
  1304. This interface has been designed so that the output from the `lex'
  1305. utility can be used without change as the definition of `yylex'.
  1306.  
  1307. In simple programs, `yylex' is often defined at the end of the Bison
  1308. grammar file.  If `yylex' is defined in a separate source file, you
  1309. need to arrange for the token-type macro definitions to be available
  1310. there.  To do this, use the `-d' option when you run Bison, so that
  1311. it will write these macro definitions into a separate header file
  1312. `NAME.tab.h' which you can include in the other source files that
  1313. need it.  *Note Invocation::.
  1314.  
  1315. In an ordinary (nonreentrant) parser, the semantic value of the token
  1316. must be stored into the global variable `yylval'.  When you are using
  1317. just one data type for semantic values, `yylval' has that type. 
  1318. Thus, if the type is `int' (the default), you might write this in
  1319. `yylex':
  1320.  
  1321.        ...
  1322.        yylval = value;  /* Put value onto Bison stack.  */
  1323.        return INT;      /* Return the type of the token.  */
  1324.        ...
  1325.  
  1326.  When you are using multiple data types, `yylval''s type is a union
  1327. made from the `%union' declaration (*note Union Decl::.).  So when
  1328. you store a token's value, you must use the proper member of the union.
  1329. If the `%union' declaration looks like this:
  1330.  
  1331.      %union {
  1332.        int intval;
  1333.        double val;
  1334.        symrec *tptr;
  1335.      }
  1336.  
  1337. then the code in `yylex' might look like this:
  1338.  
  1339.        ...
  1340.        yylval.intval = value;  /* Put value onto Bison stack.  */
  1341.        return INT;      /* Return the type of the token.  */
  1342.        ...
  1343.  
  1344.  If you are using the `@N'-feature (*note Action Features::.) in
  1345. actions to keep track of the textual locations of tokens and
  1346. groupings, then you must provide this information in `yylex'.  The
  1347. function `yyparse' expects to find the textual location of a token
  1348. just parsed in the global variable `yylloc'.  So `yylex' must store
  1349. the proper data in that variable.  The value of `yylloc' is a
  1350. structure, and you need only initialize the members that are going to
  1351. be used by the actions.  The four members are called `first_line',
  1352. `first_column', `last_line' and `last_column'.  Note that the use of
  1353. this feature makes the parser noticeably slower.
  1354.  
  1355. When you use the Bison declaration `%pure_parser' to request a pure,
  1356. reentrant parser, the global communication variables `yylval' and
  1357. `yylloc' cannot be used.  (*Note Pure Decl::.)  In such parsers the
  1358. two global variables are replaced by pointers passed as arguments to
  1359. `yylex'.  You must declare them as shown here, and pass the
  1360. information back by storing it through those pointers.
  1361.  
  1362.      yylex (lvalp, llocp)
  1363.           YYSTYPE *lvalp;
  1364.           YYLTYPE *llocp;
  1365.      {
  1366.        ...
  1367.        *lvalp = value;  /* Put value onto Bison stack.  */
  1368.        return INT;      /* Return the type of the token.  */
  1369.        ...
  1370.      }
  1371.  
  1372.  
  1373. 
  1374. File: bison.info,  Node: Error Reporting,  Next: Action Features,  Prev: Lexical,  Up: Interface
  1375.  
  1376. The Error Reporting Function `yyerror'
  1377. ======================================
  1378.  
  1379. The Bison parser expects to call an error reporting function named
  1380. `yyerror', which is supplied by you.  It is called by `yyparse'
  1381. whenever a syntax error is found, and it receives one argument, a
  1382. string which can be `"parse error"' or `"parser stack overflow"'. 
  1383. (The latter is unlikely, since you have to work really hard to
  1384. overflow the automatically-extended Bison parser stack.)
  1385.  
  1386. The following definition suffices in simple programs:
  1387.  
  1388.      yyerror (s)
  1389.           char *s;
  1390.      {
  1391.  
  1392.        fprintf (stderr, "%s\n", s);
  1393.      }
  1394.  
  1395. After `yyerror' returns to `yyparse', the latter will attempt error
  1396. recovery if you have written suitable error recovery grammar rules
  1397. (*note Error Recovery::.).  If recovery is impossible, `yyparse' will
  1398. immediately return 1.
  1399.  
  1400. The global variable `yynerr' contains the number of syntax errors
  1401. encountered so far.
  1402.  
  1403.  
  1404.